package com.atguigui.leetcode;

/**
 * 848.二进制间距
 * <p>
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/4/24 8:40
 */
public class P868BinaryGap {
    public static void main(String[] args) {
        Solution solution = new P868BinaryGap().new Solution();
        // TO TEST
        System.out.println(solution.binaryGap(13));

    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int binaryGap(int n) {
            //数字转二进制字符
            String binStr = Integer.toBinaryString(n);
            System.out.println(binStr);

            int ans = 0;
            //表示第一个1
            boolean flag = false;
            int index = 0;
            for (int i = 0; i < binStr.length(); i++) {
                //截取一位数
                String str = binStr.substring(i, i + 1);
                if (flag) {
                    //判断第二个1
                    if ("1".equalsIgnoreCase(str)) {
                        ans = Math.max(ans, i - index);
                        index = i;
                    }

                } else {
                    //判断第一个1
                    if ("1".equalsIgnoreCase(str)) {
                        index = i;
                        flag = true;
                    }
                }

            }

            return ans;
        }
    }
}
